package com.lzx.iteam.widget;

import android.content.Context;
import android.graphics.Camera;
import android.graphics.Matrix;
import android.view.animation.Animation;
import android.view.animation.Transformation;

/**
 * @author zhaoxuyang
 *
 */
public class RotateAnimation extends Animation{

	private int centerx;
	private int centery;
	private float fromDegree;
	private float toDegree;
	private Context context;
	private MyCamera camera;
	private boolean isY;
	
	public RotateAnimation(Context context){
		this.context = context;
	}
    public void setConfig(int centerx,int centery,float fromDegree,float toDegree,boolean isY){
        this.centerx = centerx;
        this.centery = centery;
        this.fromDegree = fromDegree;
        this.toDegree = toDegree;
        this.isY = isY;
    }
	
	@Override
	public void initialize(int width, int height, int parentWidth, int parentHeight) {
	    super.initialize(width, height, parentWidth, parentHeight);
	    this.camera = new MyCamera();
	}
	
	@Override
	protected void applyTransformation(float interpolatedTime, Transformation t) {
		float degree = fromDegree+(toDegree-fromDegree)*interpolatedTime;
		Matrix matrix = t.getMatrix();
		
		if(degree>76){
			degree = 90;
			camera.save();
			if(isY){
			    camera.rotateY(degree);
			}else{
			    camera.rotateX(degree);
			}
			camera.getMatrix(matrix);
			camera.restore();
		}else if(degree<-76){
			degree = -90;
			camera.save();
			if(isY){
                camera.rotateY(degree);
            }else{
                camera.rotateX(degree);
            }
			camera.getMatrix(matrix);
			camera.restore();
		}else{
			camera.save();
			float center = 0;
			if(isY){
                center = centerx;
            }else{
                center = centery;
            }
			camera.translate(0, 0, center);
			if(isY){
                camera.rotateY(degree);
            }else{
                camera.rotateX(degree);
            }
            camera.translate(0, 0, -center);
			camera.getMatrix(matrix);
			camera.restore();
		}
		matrix.preTranslate(-centerx, -centery);
		matrix.postTranslate(centerx, centery);
	}
	
	public void destroy(){
	    camera = null;
        camera.destroy();
	}
	
	
	class MyCamera extends Camera{
	    
	    public void destroy(){
	        try {
                finalize();
            } catch (Throwable e) {
                e.printStackTrace();
            }
	    }
	    @Override
	    protected void finalize() throws Throwable {
	        super.finalize();
	    }
	}
}
